package com.dduggs.rocketmq.mqtest;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.dduggs.exception.ServiceException;
import com.dduggs.rocketmq.BaseConsumer;
import com.dduggs.rocketmq.MsgObj;
import com.dduggs.rocketmq.Topic;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.List;

@Service
public class MessageConsumeService extends BaseConsumer {

    protected final Logger logger = LoggerFactory.getLogger(MessageConsumeService.class);


    @Override
    @PostConstruct
    public void init() throws MQClientException {
        super.init();
    }

    @Override
    public Class<? extends Topic> getTopic() {

        return PushMessageTopic.class;
    }

    @Override
    public void doLogErrorConsumeMessage(MsgObj msgObj) {

    }

    @Override
    public ConsumeConcurrentlyStatus doConsumeMessage(MsgObj msgObj) {

        List<Serializable> msgList = msgObj.getMsgList();
        if (CollectionUtils.isEmpty(msgList)) {
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        try {
            for (Serializable message : msgList) {
                if (message instanceof String) {
                    System.out.println(message);
                }
            }
        } catch (Exception exception) {

            logger.error("consume is failed {}-{},msgId={}", new Object[]{topic.getTopic(), topic.getTags(), msgObj.getMsgId()});
            logger.error(topic.getTags(), exception);

            if (exception instanceof ServiceException) {
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }


}
